package com.bsi.core.exception;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;

/*
 * Author: liusongs
 * Date: 2019/12/16 16:01
 * Content:全局异常处理器，进行处理异常信息
 */
public class ResponseEntityExceptionHandlerEx implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(ResponseEntityExceptionHandlerEx.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        printLog(request, ex, handler);
        response.setHeader("Content-type", "application/json;charset=utf-8");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            String res = null;
            if (ex instanceof BusinessException) {
                res = JSONObject.toJSONString(ResponseEntity.createError(SystemCode.ParamError, ex.getMessage()));
            } else if (ex instanceof BindException) {
                BindException bindException = (BindException) ex;
                List<ObjectError> allErrors = bindException.getAllErrors();
                StringBuilder builder = new StringBuilder();
                allErrors.forEach(objectError -> {
                    builder.append(objectError.getDefaultMessage() + "  ");
                });
                res = JSONObject.toJSONString(ResponseEntity.createError(SystemCode.ParamError, builder.toString()));
            } else {
                res = JSONObject.toJSONString(ResponseEntity.createError(SystemCode.ParamError));
            }
            outputStream.print(new String(res.getBytes(), "iso-8859-1"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }

    /***
     *  打印日志
     * @param request
     * @param ex
     * @param handler
     */
    public void printLog(HttpServletRequest request, Exception ex, Object handler) {
        logger.error("========================业务异常开始=======================");
        logger.error("请求路径为===>>:{}", request.getRequestURI());
        logger.error("系统异常===>>", ex);
        for (Enumeration<String> parameterNames = request.getParameterNames(); parameterNames.hasMoreElements(); ) {
            String name = parameterNames.nextElement();
            logger.error("请求参数名为:{},请求参数值为:{}", name, request.getParameter(name));
        }
        logger.error("========================业务异常结束=======================");
    }
}
